package com.wjjun.base.ui.window

import android.os.Bundle
import android.view.LayoutInflater
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatDialog
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.wjjun.base.BR
import com.wjjun.base.ui.activity.BaseActivity
import com.wjjun.base.ui.listener.IViewListener
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel
import com.wjjun.base.utils.ViewModelFactory

/**
 * 基础绑定弹窗
 * author : wangjunjun
 * date   : 2022/6/8
 * desc   :
 */
abstract class BaseDialog<VM : BaseWindowViewModel, VD : ViewDataBinding>(val context: BaseActivity) :
        AppCompatDialog(context), IViewListener {

    protected lateinit var viewDataBinding: VD
    protected lateinit var viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        buildViewModel()
        buildViewBinding()
        bindViewModel()

        initLayout()
        initViews()
        initContent()
    }

    open fun buildViewModel() {
        if( isNewViewModel()){
            viewModel = ViewModelFactory.createNewViewModel(
                context,
                this.javaClass,
                BaseWindowViewModel::class.java)
        }else{
            viewModel = ViewModelFactory.createViewModel(
                context,
                this.javaClass,
                BaseWindowViewModel::class.java)
        }
    }

    open fun isNewViewModel() :Boolean{
        return false
    }

    open fun buildViewBinding() {
        var layoutId = getLayoutId()
        if( layoutId == 0){
            layoutId = viewModel.getLayoutId()
        }
        viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, null, false)
        setContentView(viewDataBinding.root)
    }

    @LayoutRes
    open fun getLayoutId(): Int {
        return 0
    }

    open fun bindViewModel() {
        viewDataBinding.setVariable(BR.viewModel, viewModel)
        viewDataBinding.setVariable(BR.listener, this)
    }

    open fun initLayout() {
        setCancelable(true)
        setCanceledOnTouchOutside(false)
    }

    open fun initViews(){

    }

    /**
     * 初始化内容
     */
    abstract fun initContent()

}